/*
 * Powered By xTOOLs
 * Dev by tao.li8@pactera.com
 * Copyright ©2009-2018 pactera.com All rights reserved.
 *
 * Generated at 2020-6-29 9:56:19
 */

package com.pactera.jep.service.yapin.coll.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pactera.jep.orm.Filter;
import com.pactera.jep.orm.Operator;
import com.pactera.jep.orm.Page;
import com.pactera.jep.orm.mybatis.entity.EntityFilter;
import com.pactera.jep.orm.mybatis.entity.Example;
import com.pactera.jep.orm.mybatis.mapper.Mapper;
import com.pactera.jep.orm.mybatis.service.MyBatisCRUDService;
import com.pactera.jep.service.yapin.coll.mapper.*;
import com.pactera.jep.service.yapin.coll.model.*;
import com.pactera.jep.service.yapin.coll.service.CollBaseInfoService;
import com.pactera.jep.service.yapin.coll.service.CollateralCatalogService;
import com.pactera.jep.service.yapin.coll.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 服务层实现
 * @author YourName
 * @date 2020-6-29 9:56:19
 */
@Service
@Transactional
public class CollBaseInfoServiceImpl extends MyBatisCRUDService<CollBaseInfo, String> implements CollBaseInfoService {

    Logger logger =  LoggerFactory.getLogger(getClass());
    // 押品编码生成前缀
    private static final String COL_NUM_KEY = "DB";
    //录入状态：新建中/暂存
    private static final String COLLATERAL_INFO_STATUS_CODE_1 = "1";
    //主标示
    private static final String WARRANT_MAIN_WARR_FLG = "1";
    //押品状态；否
    private static final String COLLATERAL_INFO_FLG_NO = "0";
    //押品状态: 草稿
    private static final String COLLATERAL_INFO_STATUS_1 = "draft";

    @Autowired
    private CollBaseInfoMapper			collBaseInfoMapper;
    @Autowired
    private WarrantInfoMapper warrantInfoMapper;
    @Autowired
    private ValueInfoMapper valueInfoMapper;
    @Autowired
    private InsurenceInfoMapper insurenceInfoMapper;
    @Autowired
    private RentalInfoMapper rentalInfoMapper;
    @Autowired
    private AccidentInfoMapper accidentInfoMapper;
    @Autowired
    private DispositionInfoMapper dispositionInfoMapper;
    @Autowired
    private CoownerMapper coownerMapper;
    @Autowired
    private CollateralCatalogService	collateralCatalogService;

    @Override
    public Mapper<CollBaseInfo, String> getMapper() {
         return collBaseInfoMapper;
    }


    @Override
    public String checkBaseInfo(ColCollBaseInfoCheckVO colCollBaseInfoCheckVO) throws Exception {

        //查询物料是否已经存在
        boolean exist = checkWarrantInfoExist(colCollBaseInfoCheckVO.getUniqWarrantTp(), colCollBaseInfoCheckVO.getUniqWarrantNo());
        if (exist){
            throw new IllegalArgumentException("权证已存在");
        }

        CollBaseInfo collBaseInfo = new CollBaseInfo();
        //生成押品编号
        String cltNo = createCltNo();
        // 主权证编号checkBaseInfo
        collBaseInfo.setUniqWarrantNo(colCollBaseInfoCheckVO.getUniqWarrantNo());
        // 主权证类型
        collBaseInfo.setUniqWarrantTp(colCollBaseInfoCheckVO.getUniqWarrantTp());
        // 抵质押类型
        CollateralCatalog collateralCatalog = getCollateralCatalog(colCollBaseInfoCheckVO.getCltTpCd());
        collBaseInfo.setCltCgyCd(collateralCatalog.getCltCgyCd());
        // 押品种类
        collBaseInfo.setCltTpCd(colCollBaseInfoCheckVO.getCltTpCd());
        //押品状态
        collBaseInfo.setStatus(COLLATERAL_INFO_STATUS_1);
        // 押品名称
        collBaseInfo.setCltNm(colCollBaseInfoCheckVO.getCltNm());
        // 押品编号
        collBaseInfo.setCltNo(cltNo);
        // 设置押品录入信息状态：暂存
        collBaseInfo.setInfoRegStatus(COLLATERAL_INFO_STATUS_CODE_1);
        collBaseInfo.setCreatedTime(new Date());
        // 设置押品合格状态：待认定S1 在表AP_SYS_CODE
        // 设置押品合格状态：合格S2
        // 设置押权状态
        // 设置经办机构
        // 设置经办人
        // 设置基本信息完整性为否
        collBaseInfo.setColInfoCompFlg(COLLATERAL_INFO_FLG_NO);
        // 设置是否虚拟加工为否
        // 设置是否二次抵押 为否
        collBaseInfo.setSecondMortgageFlg(COLLATERAL_INFO_FLG_NO);
        //  新增押品基本信息
        collBaseInfoMapper.insert(collBaseInfo);
        String cltId = collBaseInfo.getCltId();
        WarrantInfo warrantInfo = new WarrantInfo();
        //主权证标识
        warrantInfo.setMainWarrFlg(WARRANT_MAIN_WARR_FLG);
        warrantInfo.setCltId(cltId);
        warrantInfo.setCltNo(cltNo);
        warrantInfo.setWarrantTpCd(colCollBaseInfoCheckVO.getUniqWarrantTp());
        warrantInfo.setWarrantNo(colCollBaseInfoCheckVO.getUniqWarrantNo());
        warrantInfo.setRegMatDt(colCollBaseInfoCheckVO.getRegMatDtStr());
        //权证录入日期
        warrantInfo.setWarrantInputDt(new Date());
        warrantInfo.setCreatedTime(new Date());
        warrantInfo.setDelflag("0");
        warrantInfoMapper.insert(warrantInfo);
        return cltId;
    }

    @Override
    public CollBaseInfo updateBaseInfo(CollBaseInfo collBaseInfo) {
        //设置押品信息完整性
        collBaseInfo.setColInfoCompFlg("1");
        collBaseInfoMapper.updateSelective(collBaseInfo);
        return collBaseInfo;
    }

    @Override
    public ColCollBaseInfoVO getBaseInfo(String cltId) {
        ColCollBaseInfoVO vo = new ColCollBaseInfoVO();
        CollBaseInfo collBaseInfo = collBaseInfoMapper.selectByPrimaryKey(cltId);
        //todo 设置币种
        BeanUtils.copyProperties(collBaseInfo,vo);
        return vo;
    }

    @Override
    public boolean addOrupdateValueInfo(ValueInfo valueInfo) {
        String valueinfoId = valueInfo.getValueinfoId();
        if (StringUtils.isNotBlank(valueinfoId)){
            //修改
            valueInfoMapper.updateSelective(valueInfo);
        }else {
            valueInfo.setCreatedTime(new Date());
            valueInfoMapper.insert(valueInfo);
        }
        return true;
    }

    @Override
    public Map<String,Object> getValueInfoList(ParamInfoListVO valueInfoListVO) {
        Example example = new Example(ValueInfo.class);
        example.createCriteria()
                .andEqualTo("cltId",valueInfoListVO.getCltId());
        PageHelper.startPage(valueInfoListVO.getPageNum(),valueInfoListVO.getPageSize());
        List<ValueInfo> valueInfos = valueInfoMapper.selectByExample(example);
        PageInfo<ValueInfo> pageInfo = new PageInfo<>(valueInfos);
        Map<String,Object> map = new HashMap<>(5);
        map.put("total",pageInfo.getTotal());
        map.put("rows",pageInfo.getList());
        return map;
    }

    @Override
    public boolean deleteValueInfo(List<String> valueinfoIds) {
        Example example = new Example(ValueInfo.class);
        example.createCriteria().andIn("valueinfoId",valueinfoIds);
        valueInfoMapper.deleteByExample(example);
        return true;
    }

    @Override
    public ValueInfo getValueInfo(String valueinfoId) {
        return valueInfoMapper.selectByPrimaryKey(valueinfoId);
    }

    @Override
    public boolean addOrUpdateInsurenceInfo(InsurenceInfo insurenceInfo) {
        String insurenceinfoId = insurenceInfo.getInsurenceinfoId();
        if (StringUtils.isNotBlank(insurenceinfoId)){
            // 修改
            insurenceInfoMapper.updateSelective(insurenceInfo);
        }else {
            insurenceInfo.setCreatedTime(new Date());
            insurenceInfoMapper.insert(insurenceInfo);
        }
        return true;
    }

    @Override
    public Map<String, Object> getInsurenceInfoList(ParamInfoListVO valueInfoListVO) {
        Example example = new Example(InsurenceInfo.class);
        example.createCriteria()
                .andEqualTo("cltId",valueInfoListVO.getCltId());
        PageHelper.startPage(valueInfoListVO.getPageNum(),valueInfoListVO.getPageSize());
        List<InsurenceInfo> insurenceInfos = insurenceInfoMapper.selectByExample(example);
        PageInfo<InsurenceInfo> pageInfo = new PageInfo<>(insurenceInfos);
        Map<String,Object> map = new HashMap<>(5);
        map.put("total",pageInfo.getTotal());
        map.put("rows",pageInfo.getList());
        return map;
    }

    @Override
    public InsurenceInfo getInsurenceInfo(String insurenceinfoId) {
        return insurenceInfoMapper.selectByPrimaryKey(insurenceinfoId);
    }

    @Override
    public boolean deleteInsurenceInfo(List<String> insurenceinfoIds) {
        Example example = new Example(InsurenceInfo.class);
        example.createCriteria().andIn("insurenceinfoId",insurenceinfoIds);
        insurenceInfoMapper.deleteByExample(example);
        return true;
    }

    @Override
    public boolean addOrUpdateWarrantInfo(WarrantInfo warrantInfo) {
        String warrantId = warrantInfo.getWarrantinfoId();
        // 查看权证是否存在
        boolean exist = checkWarrantInfoExist(warrantInfo.getWarrantTpCd(), warrantInfo.getWarrantNo());
        if (StringUtils.isNotBlank(warrantId)){
            WarrantInfo w = warrantInfoMapper.selectByPrimaryKey(warrantId);
            // 修改 校验是否是原来的
            if (exist && (!w.getWarrantTpCd().equals(warrantInfo.getWarrantTpCd()) ||
                    !w.getWarrantNo().equals(warrantInfo.getWarrantNo()))){
                throw new IllegalArgumentException("权证已存在");
            }
            warrantInfoMapper.updateSelective(warrantInfo);
        }else {
            if (exist){
                throw new IllegalArgumentException("权证已存在");
            }
            // 新增
            warrantInfo.setCreatedTime(new Date());
            warrantInfo.setDelflag("0");
            warrantInfoMapper.insert(warrantInfo);
        }
        return true;
    }

    @Override
    public Map<String, Object> getWarrantInfoList(ParamInfoListVO valueInfoListVO) {
        Example example = new Example(WarrantInfo.class);
        example.createCriteria()
                .andEqualTo("cltId",valueInfoListVO.getCltId())
                .andEqualTo("delflag","0");
        PageHelper.startPage(valueInfoListVO.getPageNum(),valueInfoListVO.getPageSize());
        List<WarrantInfo> warrantInfos = warrantInfoMapper.selectByExample(example);
        PageInfo<WarrantInfo> pageInfo = new PageInfo<>(warrantInfos);
        Map<String,Object> map = new HashMap<>(5);
        map.put("total",pageInfo.getTotal());
        map.put("rows",pageInfo.getList());
        return map;
    }

    @Override
    public WarrantInfo getWarrantInfo(String warrantinfoId) {
        return warrantInfoMapper.selectByPrimaryKey(warrantinfoId);
    }

    @Override
    public boolean deleteWarrantInfo(List<String> warrantinfoIds) {
        boolean isMainWarrFlg = false;
        Example example = new Example(WarrantInfo.class);
        example.createCriteria().andNotIn("warrantinfoId",warrantinfoIds);
        List<WarrantInfo> warrantInfos = warrantInfoMapper.selectByExample(example);
        for (WarrantInfo w:warrantInfos) {
            if (WARRANT_MAIN_WARR_FLG.equals(w.getMainWarrFlg())){
                isMainWarrFlg = true;
                break;
            }
        }

        // 还存在主标示
        if (isMainWarrFlg){
            Example example2 = new Example(WarrantInfo.class);
            example2.createCriteria().andIn("warrantinfoId",warrantinfoIds);
            List<WarrantInfo> warrantInfos2 = warrantInfoMapper.selectByExample(example2);
            for (WarrantInfo w:warrantInfos2) {
                w.setDelflag("1");
                warrantInfoMapper.updateSelective(w);
            }
        }else {
            throw new IllegalArgumentException("需要保留一个主权证");
        }
        return true;
    }

    @Override
    public boolean addOrUpdateRentalInfo(RentalInfo rentalInfo) {
        String rentalinfoId = rentalInfo.getRentalinfoId();
        if (StringUtils.isNotBlank(rentalinfoId)){
            rentalInfoMapper.updateSelective(rentalInfo);
        }else {
            rentalInfo.setCreatedTime(new Date());
            rentalInfoMapper.insert(rentalInfo);
        }
        return true;
    }

    @Override
    public Map<String, Object> getRentalInfoList(ParamInfoListVO valueInfoListVO) {
        Example example = new Example(RentalInfo.class);
        example.createCriteria()
                .andEqualTo("cltId",valueInfoListVO.getCltId());
        PageHelper.startPage(valueInfoListVO.getPageNum(),valueInfoListVO.getPageSize());
        List<RentalInfo> rentalInfos = rentalInfoMapper.selectByExample(example);
        PageInfo<RentalInfo> pageInfo = new PageInfo<>(rentalInfos);
        Map<String,Object> map = new HashMap<>(5);
        map.put("total",pageInfo.getTotal());
        map.put("rows",pageInfo.getList());
        return map;
    }

    @Override
    public RentalInfo getRentalInfo(String rentalinfoId) {
        return rentalInfoMapper.selectByPrimaryKey(rentalinfoId);
    }

    @Override
    public Map<String, Object> getRentalInfoByCltId(String cltId) {
        RentalInfoListVO rentalInfoListVO = new RentalInfoListVO();
        List<EntityFilter> list = new ArrayList<>();
        list.add(new EntityFilter(RentalInfo.class,"cltId", Operator.EQ,cltId));
        List<RentalInfo> rentalInfos = rentalInfoMapper.selectByFilter(list);
        PageInfo<RentalInfo> pageInfo = new PageInfo<>(rentalInfos);
        List<RentalInfo> rentalInfoList = pageInfo.getList();
        PageHelper.startPage(rentalInfoListVO.getPageNum(),rentalInfoListVO.getPageSize());
        Map<String, Object> result = new HashMap();
        result.put("total",pageInfo.getTotal());
        result.put("rows",rentalInfoList);
        return result;
    }

    @Override
    public boolean deleteRentalInfo(List<String> rentalinfoIds) {
        Example example = new Example(RentalInfo.class);
        example.createCriteria().andIn("rentalinfoId",rentalinfoIds);
        rentalInfoMapper.deleteByExample(example);
        return true;
    }

    @Override
    public Map<String, Object> getAccidentInfoList(ParamInfoListVO valueInfoListVO) {
        Example example = new Example(AccidentInfo.class);
        example.createCriteria()
                .andEqualTo("cltId",valueInfoListVO.getCltId());
        PageHelper.startPage(valueInfoListVO.getPageNum(),valueInfoListVO.getPageSize());
        List<AccidentInfo> accidentInfos = accidentInfoMapper.selectByExample(example);
        PageInfo<AccidentInfo> pageInfo = new PageInfo<>(accidentInfos);
        Map<String,Object> map = new HashMap<>(5);
        map.put("total",pageInfo.getTotal());
        map.put("rows",pageInfo.getList());
        return map;
    }

    @Override
    public Map<String, Object> getAccidentInfoByCltId(String cltId) {
        AccidentInfoListVO accidentInfoListVO = new AccidentInfoListVO();
        List<EntityFilter> list = new ArrayList<>();
        list.add(new EntityFilter(AccidentInfo.class,"cltId", Operator.EQ, cltId));
        List<AccidentInfo> accidentInfos = accidentInfoMapper.selectByFilter(list);
        PageInfo<AccidentInfo> pageInfo = new PageInfo<>(accidentInfos);
        List<AccidentInfo> accidentInfoList = pageInfo.getList();
        PageHelper.startPage(accidentInfoListVO.getPageNum(),accidentInfoListVO.getPageSize());
        Map<String, Object> result = new HashMap();
        result.put("total",pageInfo.getTotal());
        result.put("rows",accidentInfoList);
        return result;
    }

    @Override
    public Map<String, Object> getBaseInfoById(String cltId) {
        CollBaseInfo collBaseInfo = collBaseInfoMapper.selectByPrimaryKey(cltId);
        Map<String, Object> objectMap = JSON.parseObject(JSON.toJSONString(collBaseInfo), new TypeReference<Map<String, Object>>() {
        });
        return objectMap;
    }

    @Override
    public boolean deleteAccidentInfo(List<String> accidentinfoIds) {
        Example example = new Example(AccidentInfo.class);
        example.createCriteria().andIn("accidentinfoId",accidentinfoIds);
        accidentInfoMapper.deleteByExample(example);
        return true;
    }

    @Override
    public DispositionInfo getDispositionInfo(String cltId) {
        DispositionInfo dispositionInfo = new DispositionInfo();
        dispositionInfo.setCltId(cltId);
        return dispositionInfoMapper.selectOne(dispositionInfo);
    }

    @Override
    public Map<String, Object> getCollBaseInfoList(CollBaseListVO collBaseListVO) {
        List<EntityFilter> list = new ArrayList<>(16);
        if (StringUtils.isNotBlank(collBaseListVO.getCltNo())){
            list.add(new EntityFilter(CollBaseInfo.class,"cltNo", Operator.EQ,collBaseListVO.getCltNo()));
        }
        if (StringUtils.isNotBlank(collBaseListVO.getCltNm())){
            list.add(new EntityFilter(CollBaseInfo.class,"cltNm",Operator.LIKE,collBaseListVO.getCltNm()));
        }
        if (StringUtils.isNotBlank(collBaseListVO.getCltOwnerNo())){
            list.add(new EntityFilter(CollBaseInfo.class,"cltOwnerNo",Operator.EQ,collBaseListVO.getCltOwnerNo()));
        }
        if (StringUtils.isNotBlank(collBaseListVO.getCltTpCd())){
            list.add(new EntityFilter(CollBaseInfo.class,"cltTpCd",Operator.EQ,collBaseListVO.getCltTpCd()));
        }
        if (StringUtils.isNotBlank(collBaseListVO.getGuarSubjectNo())){
            list.add(new EntityFilter(CollBaseInfo.class,"guarSubjectNo",Operator.EQ,collBaseListVO.getGuarSubjectNo()));
        }
        if (StringUtils.isNotBlank(collBaseListVO.getHandUserNo())){
            list.add(new EntityFilter(CollBaseInfo.class,"handUserNo",Operator.EQ,collBaseListVO.getHandUserNo()));
        }
        if (StringUtils.isNotBlank(collBaseListVO.getHandOrgNo())){
            list.add(new EntityFilter(CollBaseInfo.class,"handOrgNo",Operator.EQ,collBaseListVO.getHandOrgNo()));
        }
        if (StringUtils.isNotBlank(collBaseListVO.getInfoRegStatus())){
            list.add(new EntityFilter(CollBaseInfo.class,"infoRegStatus",Operator.EQ,collBaseListVO.getInfoRegStatus()));
        }

        PageHelper.startPage(collBaseListVO.getPageNum(),collBaseListVO.getPageSize());
        List<CollBaseInfo> collBaseInfos = collBaseInfoMapper.selectByFilter(list);
        PageInfo<CollBaseInfo> pageInfo = new PageInfo<>(collBaseInfos);
        List<CollBaseInfo> collBaseInfoList = pageInfo.getList();
        List<CollBaseListVO> cl = new ArrayList<>(collBaseInfoList.size());
        if (!collBaseInfoList.isEmpty()){
            for (CollBaseInfo c:collBaseInfoList) {
                CollBaseListVO cvo = new CollBaseListVO();
                BeanUtils.copyProperties(c,cvo);
                cl.add(cvo);
            }
        }
        Map<String,Object> map = new HashMap<>(5);
        map.put("total",pageInfo.getTotal());
        map.put("rows",cl);
        return map;
    }

    @Override
    public Map<String, Object> getValueInfoByCltId(String cltId) {
        ValueInfoListVO valueInfoListVO = new ValueInfoListVO();
        List<EntityFilter> list = new ArrayList<>();
        list.add(new EntityFilter(ValueInfo.class,"cltId", Operator.EQ,cltId));
        List<ValueInfo> valueInfos = valueInfoMapper.selectByFilter(list);
        PageInfo<ValueInfo> pageInfo = new PageInfo<>(valueInfos);
        List<ValueInfo> ValueInfoList = pageInfo.getList();
        PageHelper.startPage(valueInfoListVO.getPageNum(),valueInfoListVO.getPageSize());
        Map<String, Object> result = new HashMap();
        result.put("total",pageInfo.getTotal());
        result.put("rows",ValueInfoList);
        return result;
    }

    @Override
    public Map<String, Object> getWarrantInfoByCltId(String cltId) {
        WarrantInfoListVO warrantInfoListVO = new WarrantInfoListVO();
        List<EntityFilter> list = new ArrayList<>();
        list.add(new EntityFilter(WarrantInfo.class,"cltId", Operator.EQ,cltId));
        List<WarrantInfo> warrantInfos = warrantInfoMapper.selectByFilter(list);
        PageInfo<WarrantInfo> pageInfo = new PageInfo<>(warrantInfos);
        List<WarrantInfo> warrantInfoList = pageInfo.getList();
        PageHelper.startPage(warrantInfoListVO.getPageNum(),warrantInfoListVO.getPageSize());
        Map<String, Object> result = new HashMap();
        result.put("total",pageInfo.getTotal());
        result.put("rows",warrantInfoList);
        return result;
    }

    @Override
    public Map<String, Object> getCoownerByCltId(String cltId){

        CoownerVO coownerVO = new CoownerVO();
        List<EntityFilter> list = new ArrayList<>();
        list.add(new EntityFilter(Coowner.class, "cltId", Operator.EQ, cltId));
        List<Coowner> coowners = coownerMapper.selectByFilter(list);
        PageInfo<Coowner> pageInfo = new PageInfo<>(coowners);
        List<Coowner> coownerList = pageInfo.getList();
        PageHelper.startPage(coownerVO.getPageNum(),coownerVO.getPageSize());
        Map<String, Object> result = new HashMap();
        result.put("total",pageInfo.getTotal());
        result.put("rows",coownerList);
        return result;
    }


    /**
     * 检查物料是否存在
     * @param warrantTp 物料类型
     * @param warrantNo 物料编号
     * @return 是否存在
     */
    private boolean checkWarrantInfoExist(String warrantTp, String warrantNo){
        boolean result = false;
        Example example = new Example(WarrantInfo.class);
        example.createCriteria()
                .andEqualTo("warrantTpCd",warrantTp)
                .andEqualTo("warrantNo",warrantNo);
        List<WarrantInfo> warrantInfos = warrantInfoMapper.selectByExample(example);
        if (!warrantInfos.isEmpty()){
            result = true;
        }
        return result;
    }


    /**
     * 生成押品编号
     */
    public synchronized String createCltNo(){
        long l = System.currentTimeMillis();
        return COL_NUM_KEY+l;
    }

    /**
     * 获取押品种类
     */
    private CollateralCatalog getCollateralCatalog(String cltTpCd){
        return collateralCatalogService.getCollateralCatalog(cltTpCd);
    }
}
